import { Select } from 'antd';
import React, { forwardRef, useEffect, useState, useMemo } from 'react';

import mcpService from '@/api/services/mcpService';
import { GetCreatedMcpListItem, GetProviderListItem } from '@/common/types';
import { Search, Segmented } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import { CircleLoading } from '@/components/loading';
import TipsModals from '@/components/modals/TipsModals';
import NotData from '@/components/NotData';
import useModal from '@/hooks/use-modal/useModal';
import { useScrollPagination } from '@/hooks/use-pagination/useVirtualScrollPagination';
import ToolsItem from '@/pages/components/tools-item/ToolsItem';
import { useRouter } from '@/router/hooks';
import useUserStore from '@/store/userStore';

import McpToolsSelect from '../McpToolsSelect';

const MCPTools = forwardRef((_, ref) => {
  const modal = useModal('select', 'delete');
  const { userInfo } = useUserStore();
  const [updateData, setUpdateData] = useState<GetProviderListItem | GetCreatedMcpListItem>();
  const [deleteData, setDeleteData] = useState<GetCreatedMcpListItem>();
  const [categoriesData, setCategoriesData] = useState<{ label: string; value: string }[]>();
  const [cateValue, setCateValue] = useState<string>();
  const [sourceValue, setSourceValue] = useState<string>('all');
  const [searchText, setSearchText] = useState<string>('');
  const [refreshKey, setRefreshKey] = useState<number>(0);
  const router = useRouter();

  const {
    data: mcpList,
    isLoading: loading,
    ScrollData,
    setData,
  } = useScrollPagination(mcpService.getMcpList, {
    pageSize: 20,
    showLoadText: false,
    params: {
      searchText,
      source: sourceValue === 'all' ? undefined : 'mine',
      categoryCN: cateValue,
    },
    refreshDeps: [sourceValue, searchText, cateValue, refreshKey],
  });

  const processedMcpList = useMemo(() => {
    if (!mcpList || mcpList.length === 0) {
      return [];
    }
    const list = mcpList.map((item) => {
      let author = '官方';
      if (item.createUser) {
        if (userInfo.userId === item.createUser.userId) {
          author = '我';
        } else {
          author = `${item.createUser?.groupName} / ${item.createUser?.userName}`;
        }
      }

      return {
        ...item,
        icon: item.avatar.includes('/') ? item.avatar : `${item.avatar}.svg`,
        author,
        isMine: item.createUser && userInfo.userId === item.createUser.userId,
      };
    });
    return list;
  }, [mcpList, userInfo.id]);

  useEffect(() => {
    getCategoriesList();
  }, []);

  const getCategoriesList = () => {
    mcpService.getCategoriesList().then((res) => {
      const options = res.map((item: any) => ({
        label: item.nameCN,
        value: item.nameCN,
        id: item.id,
        type: item.type,
      }));
      options.unshift({
        label: '全部类型',
        value: '',
      });
      setCategoriesData(options);
      if (options.length > 0) {
        setCateValue(options[0].value);
      }
    });
  };

  const handleUpdateModel = (value: any) => {
    modal.select.close();
  };

  const handleCardClick = (value: GetCreatedMcpListItem) => {
    mcpService.getDetail(value?.id).then((res) => {
      setUpdateData(res);
      router.pushQuery('/mcp/orchestration', res);
    });
  };

  const handleDeleteModel = (value: GetCreatedMcpListItem) => {
    setDeleteData(value);
    modal.delete.open();
  };

  const onDeleteModel = () => {
    if (deleteData) {
      modal.delete.startLoading();
      mcpService
        .deleteMcp(deleteData?.id)
        .then((res) => {
          setRefreshKey((prev) => prev + 1);
          modal.delete.close();
        })
        .finally(() => {
          modal.delete.stopLoading();
        });
    }
  };

  const handleChange = (value: string) => {
    setCateValue(value);
    setRefreshKey((prev) => prev + 1);
  };

  const handleSourceChange = (value: string) => {
    setSourceValue(value);
    setRefreshKey((prev) => prev + 1);
  };

  const handleSearchText = (value: string) => {
    setSearchText(value);
    setRefreshKey((prev) => prev + 1);
  };

  return (
    <>
      <div className="flex items-center justify-between gap-3">
        <div className="flex gap-2">
          <Segmented
            className="border border-[var(--line-3)] !bg-white"
            value={sourceValue}
            onChange={(value) => handleSourceChange(value as string)}
            options={[
              { label: '全部来源', value: 'all' },
              { label: '我创建的', value: 'mine' },
            ]}
          />
          <Select
            value={cateValue}
            className="!w-[160px]"
            onChange={handleChange}
            options={categoriesData}
          />
          {sourceValue === 'all' && (
            <div className="w-[240px]">
              <Search
                placeholder="搜索"
                value={searchText}
                onChange={(e) => handleSearchText(e.target.value)}
              />
            </div>
          )}
          {sourceValue === 'mine' && (
            <div className="w-[240px]">
              <Search
                placeholder="搜索我创建的"
                value={searchText}
                onChange={(e) => handleSearchText(e.target.value)}
              />
            </div>
          )}
        </div>
        <div
          className="flex h-[32px] w-[128px] cursor-pointer items-center justify-center rounded-md border border-@brand-color !text-@brand-color"
          onClick={modal.select.open}
        >
          <SvgIcon icon="message-ic13" size="15" className="mr-1" />
          添加MCP工具
        </div>
      </div>

      {mcpList.length > 0 && (
        <ScrollData className="h-[calc(100vh-190px)] overflow-y-auto overflow-x-hidden">
          <div className="mt-4 grid grid-cols-1 gap-4 pr-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
            {processedMcpList.map((item) => (
              <ToolsItem
                key={item.id}
                {...item}
                onEdit={() => handleCardClick(item)}
                onDelete={() => handleDeleteModel(item)}
              />
            ))}
          </div>
        </ScrollData>
      )}

      {mcpList.length === 0 && !loading && (
        <div className="h-full text-center">
          <NotData />
        </div>
      )}

      {loading && (
        <div className="absolute inset-0 flex items-center justify-center">
          <CircleLoading />
        </div>
      )}

      <McpToolsSelect
        open={modal.select.isOpen}
        onCancel={modal.select.close}
        onOk={handleUpdateModel}
        selectProvider={mcpList as any}
      />

      <TipsModals
        open={modal.delete.isOpen}
        onOk={onDeleteModel}
        confirmLoading={modal.delete.isLoading}
        onCancel={modal.delete.close}
      >
        <div>删除后无法恢复,确认删除？</div>
      </TipsModals>
    </>
  );
});

export default MCPTools;
